package weiconsole;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import weibo4j.Account;
import weibo4j.Oauth;
import weibo4j.Users;
import weibo4j.Weibo;
import weibo4j.http.AccessToken;
import weibo4j.model.User;
import weibo4j.model.WeiboException;
import weibo4j.util.BareBonesBrowserLaunch;

public class UserManager {
	private AccessToken accessToken;
	private User currentUser = null;
	public boolean loggedIn = false;
	
	public UserManager() {
		this.accessToken = null;
		this.currentUser = null;
		this.loggedIn = false;
		
		regModule();
	}
	
	public void regModule() {
		/* register user manager module */
		Module umod = new Module("weiconsole.UserManager", this);
		umod.addFunction("login");
		umod.addFunction("myprofile");
		Main.registerModule(umod);
	}
	
	public void tryToLogin() {
		String access_token = Main.userProps.getProperty("weiconuser.accessToken", "");
		if (access_token.equals("")) {
			System.out.println("It seems that this is the first time you use weiconsole, please type `login' to set user. " +
					"user information will be saved to ~/.weiconuser.\n");
			return;
		}
		
        Main.weibo = new Weibo();
        Main.weibo.setToken(access_token);
        
        Account ac = new Account();
        String uid = "";
        try {
        	 uid = ac.getUid().get("uid").toString();
        } catch (Exception e) {
        	Main.error("invalid access token. please try `login' to get a new one");
        	return;
        }
        
        //String uid = accessToken.getUid();
        Users um = new Users();
        currentUser = null;
        try {
            currentUser = um.showUserById(uid);
            System.out.println("login successfully, hello " + currentUser.getName() + "!");
        }catch (WeiboException e) {
            e.printStackTrace();
        } catch (Exception e) {
        	Main.error("unknown error occured while fetching user profile");
        } 
        
        loggedIn = true;
	}
	
	public void login(String args[]) {
		Oauth oauth = new Oauth();
		try { 
			BareBonesBrowserLaunch.openURL(oauth.authorize("code"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.print("please copy your code here: ");
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String code = new String("");
		try {
			code = br.readLine();
		} catch (Exception e) {
			e.printStackTrace();
		}
		accessToken = null;
        try {
            accessToken = oauth.getAccessTokenByCode(code);
		} catch (WeiboException e) {
			if(401 == e.getStatusCode()){
			}else{
				e.printStackTrace();
			}
		}
      
		String access_token = accessToken.getAccessToken();
		Main.userProps.setProperty("weiconuser.accessToken", access_token);
		try { 
			FileOutputStream fout = new FileOutputStream(Main.userPropsPath); 
			Main.userProps.store(fout, "user information for weiconsole");
			fout.close(); 
		} 
		catch (IOException ex) { 
			Main.error("cannot save user information to ~/.weiconuser"); 
		} 
		
        Main.weibo = new Weibo();
        Main.weibo.setToken(access_token);
        
        Account ac = new Account();
        String uid = "";
        try {
        	 uid = ac.getUid().get("uid").toString();
        } catch (Exception e) {
        	Main.error("failed to get uid(" + e.toString() + ")");
        }
        
        //String uid = accessToken.getUid();
        Users um = new Users();
        currentUser = null;
        try {
            currentUser = um.showUserById(uid);
            System.out.println("login successfully, hello " + currentUser.getName() + "!");
        }catch (WeiboException e) {
            e.printStackTrace();
        } catch (Exception e) {
        	Main.error("unknown error occured while fetching user profile");
        } 
        
        loggedIn = true;
	}
	
	public void myprofile(String args[]) {
		if (!Main.checkLoggedIn()) return;
		System.out.println("name: " + currentUser.getName());
		System.out.println("gender: " + getGender(currentUser.getGender()));
		System.out.println("location: " + currentUser.getLocation());
		System.out.println("description: " + ((currentUser.getDescription().equals(""))? "null" : currentUser.getDescription()));
		System.out.println("member since: " + currentUser.getCreatedAt());
		System.out.println("statuses: " + currentUser.getStatusesCount());
        System.out.println("friends: " + currentUser.getFriendsCount());
        System.out.println("followers: " + currentUser.getFollowersCount());
		System.out.println("favourites: " + currentUser.getFavouritesCount());
	}
	
	private String getGender(String gender) {
		if (gender.equals("f")) return "female";
		else if (gender.equals("m")) return "male";
		else return "error";
	}
	
	public AccessToken getAccessToken() {
		return accessToken;
	}
	
	public User getCurrentUser() {
		return currentUser;
	}
}
